package com.cn.pet.controller;

import com.cn.pet.model.request.ItemQueryRequest;
import com.cn.pet.service.BrandService;
import com.cn.pet.service.ItemService;
import com.cn.pet.service.KeywordService;
import com.cn.pet.util.ExcelUtil;
import com.cn.pet.vo.ItemVO;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class ItemController {

    @Autowired
    ItemService itemService;

    @Autowired
    BrandService brandService;

    @Autowired
    KeywordService keywordService;

    @RequestMapping(value = "/items", method = RequestMethod.GET)
    public String firstComing(Model model) {
        return "item_list";
    }

    @ResponseBody
    @RequestMapping(value = "/items", method = RequestMethod.POST)
    public List<ItemVO> searchItemList(@RequestBody ItemQueryRequest itemQueryRequest, Model model) {
        return itemService.findItemList(itemQueryRequest);
    }

    @RequestMapping("/items/export")
    public void exportItems(@RequestBody ItemQueryRequest itemQueryRequest, HttpServletResponse response){
        try{
//            String fileName = "商品列表.xls";
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
//            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
//            XSSFWorkbook workBook = new XSSFWorkbook();
            HSSFWorkbook workbook = new HSSFWorkbook();
            String[] headers = itemService.getExcelHeaders(itemQueryRequest.getPlatformId());
            List<List<Object>> itemList = itemService.getExportItems(itemQueryRequest);
            ExcelUtil.exportExcel(workbook,0,"sheet1",headers,itemList);
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
